import Vue from "vue";
import VueRouter from "vue-router";
import Home from "./views/Home.vue";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      redirect: "/home"
    },
    // home页面
    {
      path: "/home",
      name: "home",
      component: Home,
      // 子页面
      children: [
        {
          path: "/home",
          redirect: "/welcome"
        },
        // welcome页面
        // @代表 ./src
        {
          path: "/welcome",
          component: () => import("@/components/Welcome.vue")
        },
        // 用户列表页面
        {
          path: "/users",
          component: () => import("@/components/UserList.vue")
        },
        // 权限列表页面
        {
          path: "/rights",
          component: () => import("@/components/RightList.vue")
        },
        // 角色列表页面
        {
          path: "/roles",
          component: () => import("@/components/RolesList.vue")
        },
        // 商品分类
        {
          path: "/categories",
          component: () => import("@/components/CategoryList.vue")
        },
        // 分类参数
        {
          path: "/params",
          component: () => import("@/components/ParamsList.vue")
        },
        // 订单列表
        {
          path: "/orders",
          component: () => import("@/components/OrderList.vue")
        },
        // 商品列表
        {
          path: "/goods",
          component: () => import("@/components/GoodsList.vue")
        },
        // 商品列表中的添加商品
        {
          path: "/goods/add",
          component: () => import("@/components/AddList.vue")
        },
        // 数据统计
        {
          path: "/reports",
          component: () => import("@/components/DataReports.vue")
        }
      ]
    },
    // 登录页面
    {
      path: "/login",
      name: "login",
      component: () => import("./views/Login.vue")
    }
  ]
});

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // 判断是否是login这个路由 是这个路由就放行
  if (to.path == "/login") return next();
  // 获取有没有令牌 如果没有令牌 去login
  const tokenStr = window.sessionStorage.getItem("token");
  if (!tokenStr) {
    window.sessionStorage.removeItem("token");
    return next("/login");
  }
  // 如果登录了 那么就放行
  next();
});

// 时间过滤器
Vue.filter("formDate", originVal => {
  const date = new Date(originVal);
  const year = date
    .getFullYear()
    .toString()
    .padStart(2, "0");
  const month = (date.getMonth() + 1 + "").toString().padStart(2, "0");
  const day = date
    .getDate()
    .toString()
    .padStart(2, "0");
  const hour = date
    .getHours()
    .toString()
    .padStart(2, "0");
  const minutes = date
    .getMinutes()
    .toString()
    .padStart(2, "0");
  const seconds = date
    .getSeconds()
    .toString()
    .padStart(2, "0");
  return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`;
});
export default router;
